package com.zhuang.chapter14.work05;

import java.util.Iterator;
import java.util.NoSuchElementException;

@SuppressWarnings("all")
public class SequenceList<T> implements Iterable<T> {
	// 存储元素的数组
	private T[] eles;
	// 当前顺序表的长度
	private int n;

	// 创建容量为capacity的SequenceList对象
	SequenceList(int capacity) {
		eles = (T[]) new Object[capacity];
	}

	// 置空顺序表
	public void clear() {
		for (int i = 0; i < n; i++) {
			eles[i] = null;
		}
		n = 0;
	}

	// 判断顺序表是否为空
	public boolean isEmpty() {
		return n == 0;
	}

	// 获取顺序表的元素个数
	public int length() {
		int count = 0;
		for (int i = 0; i < n; i++) {
			if (eles[i] != null) {
				count++;
			}
		}
		return count;
	}

	// 返回顺序表中的第i个元素
	public T get(int i) {
		return eles[i];
	}

	// 在顺序表的第i个元素之前插入一个元素t
	public void insert(int i, T t) {
		for (int j = n - 1; j >= i; j--) {
			eles[j + 1] = eles[j];
		}
		eles[i] = t;
		n++;
	}

	// 向顺序表中添加一个元素t
	public void insert(T t) {
		insert(n, t);
	}

	// 删除并返回顺序表中的第i个元素
	public T remove(int i) {
		T oldelement = eles[i];
		for (int j = i + 1; j < n; j++) {
			eles[j - 1] = eles[j];
		}
		eles[--n] = null;
		return oldelement;
	}

	// 返回顺序表中首次出现元素t的位置，若不存在返回-1
	public int indexOf(T t) {
		if (eles == null) {
			for (int i = 0; i < n; i++) {
				if (eles[i] == null) {
					return i;
				}
			}
		} else {
			for (int i = 0; i < n; i++) {
				if (eles.equals(eles[i])) {
					return i;
				}
			}
		}
		return -1;
	}

	public void print() {
		for (T t : eles) {
			if (t != null) {
				System.out.print(t + ",");
			}
		}
	}

	@Override
	public Iterator<T> iterator() {
		return new SIterator<T>(this);
	}

	class SIterator<T> implements Iterator<T> {

		private int current = 0;

		private SequenceList<T> sequenceList;

		public SIterator(SequenceList<T> sequenceList) {
			this.sequenceList = sequenceList;
		}

		@Override
		public boolean hasNext() {
			// 判断是否还有下一个
			return current < sequenceList.length();
		}

		@Override
		public T next() {
			// 看是否还有下一个
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			return sequenceList.eles[current++];
		}

		public void remove() {
			SequenceList.this.remove(--current);
		}
	}
}
